<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-MELANGE.
 *
 * PHP-MELANGE is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-MELANGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-MELANGE; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-melange
 * @subpackage  cms
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */

require_once("mvc/action/Action.php");
require_once("cms/content/om/ContentPeer.php");
require_once("cms/content/om/ContentI18nPeer.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, ContentForm &$form, Request &$request, Response &$response) {

        $errors = new ActionMessages();

        $contentI18n =& $form->getContentI18n();
        $contentI18n->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));

        $content =& $contentI18n->getContent();

        $default = $request->getContext()->getInitParameter(
                _Core::DEFAULT_LANGUAGE);

        if($contentI18n->getLanguageCode() == $default) {
        	
        	// Get the uri
        	$content->setUri(URL::sanitize_title_with_dashes($contentI18n->getName()));
        	
        	// Uri unique check;
        	$c = new Criteria();
        	$c->add(ContentPeer::CATEGORY_ID, $content->getCategoryId());
        	$c->add(ContentPeer::URI, $content->getUri());
        	if($contentI18n->getContentId() > 0) {
        		$c->add(ContentPeer::CONTENT_ID, $contentI18n->getContentId(), Criteria::NOT_EQUAL);
        	}
        	$check = ContentPeer::doSelectOne($c);

        	// Save error and back to form.
        	if(!is_null($check)) {
        	   $errors->add(ActionMessage::GLOBAL_MESSAGE,
                    new ActionMessage("error.uri", true));
                $this->saveErrors($request, $errors);
                return $mapping->getInputForward();	
        	}        	

            if(strlen($form->getDay()) > 0 && strlen($form->getMonth()) > 0 && strlen($form->getYear()) > 0) {
                $content->setDate($form->getYear()."-".$form->getMonth()."-".$form->getDay());
            } else {
                $content->setDate("0000-00-00");
                $content->setDate(null);
            }

        }

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            $formImage =& $form->getFormImage();

            // process image
            if(!$form->getDeleteImage() && $formImage["size"] > 0) {

                $image = $content->getImageRelatedByImageId();
                $thumb = $content->getImageRelatedByThumbnailId();

                require_once("cms/core/util/ImageProperties.php");
                $properties = new ImageProperties(
                    $request->getContext()->getInitParameter(_Core::SETTING_LIST)
                );

                require_once("cms/core/util/ImageProcessor.php");
                ImageProcessor::process(
                    $conn, $errors, $formImage,
                    $properties, $image, $thumb
                );

                // Set the generated ids
                $content->setThumbnailId($thumb->getImageId());
                $content->setImageId($image->getImageId());

            } else if($form->getDeleteImage()) {

                $image = $content->getImageRelatedByImageId();
                $thumb = $content->getImageRelatedByThumbnailId();

                require_once("cms/core/om/BinaryFilePeer.php");

                BinaryFilePeer::doDelete($thumb->getBinaryFile(), $conn);
                BinaryFilePeer::doDelete($image->getBinaryFile(), $conn);
            }

            // Save content
            if($contentI18n->getContentI18nId() > 0) {

                // Update contentI18n
            	ContentI18nPeer::doUpdate($contentI18n, $conn);

                // Update content
            	$content->setContentId($contentI18n->getContentId());
                ContentPeer::doUpdate($content, $conn);
                
                if($contentI18n->getLanguageCode() == $default) {
                	
                	// Get the old uri of this content
                	$oldContent = ContentPeer::retrieveByPK($content->getContentId());
                	
                	require_once 'cms/content/om/ContentLinkPeer.php';
                	
                	// Is there a content-link linked to this page ?
                    $c = new Criteria();
                    $c->add(ContentLinkPeer::CATEGORY_ID, $content->getCategoryId());
                    $c->add(ContentLinkPeer::LINK, $oldContent->getUri());
                    $link = ContentLinkPeer::doSelectOne($c, $conn);
                                    
                    // Update the content-link table for the correct uri's
                    if(!is_null($link)) {
                    	$c = new Criteria();
                    	$c->add(ContentLinkPeer::CONTENT_LINK_ID, $link->getContentLinkId());
                    	$c->add(ContentLinkPeer::LINK, $olduri);
                    	ContentLinkPeer::doUpdate($c, $conn);
                    }
                    
                    require_once 'cms/menu/om/MenuItemPeer.php';
                    
                    // Is there a menu-item-link linked to this page ?
                    $c = new Criteria();
                    $c->add(MenuItemPeer::CATEGORY_ID, $content->getCategoryId());
                    $c->add(MenuItemPeer::LINK, $oldContent->getUri());
                    $link = MenuItemPeer::doSelectOne($c, $conn);
                                    
                    // Update the content-link table for the correct uri's
                    if(!is_null($link)) {
                        $c = new Criteria();
                        $c->add(MenuItemPeer::MENU_ITEM_ID, $link->getMenuItemId());
                        $c->add(MenuItemPeer::LINK, $content->getUri());
                        MenuItemPeer::doUpdate($c, $conn);
                    }
                    
                }

            } else {

                // An initial default language content is added.
                if(strlen($contentI18n->getContentId()) == 0) {
                    $language = $request->getContext()->
                        getInitParameter(_Core::DEFAULT_LANGUAGE);
                    $content->setPosition($content->getMaxPosition() + 1);
                    $contentI18n->setContentId(ContentPeer::doInsert($content, $conn));
                    $contentI18n->setLanguageCode($language);
                }
                $contentI18n->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                $contentI18n->setActive(_Core::AUTO_ACTIVATE);
                $contentI18n->setContentI18nId(
                    ContentI18nPeer::doInsert($contentI18n, $conn));
            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save", true));
            $this->log->error($e->getMessage());
        }


        // Save errors and return to form
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        // Reset listing page
        $session  = $request->getSession();
        $listForm = $session->getAttribute("php-cms/contentListForm");
        if(!is_null($listForm)) {
            $listForm->setPage(1);
            $session->setAttribute("php-cms/contentListForm", $listForm);
        }


        // Add content to search index
        if($request->getContext()->getInitParameter(_Core::SEARCH) === true) {
        	$contentI18n->addToIndex($request->getContext()->
                getInitParameter(_Core::SEARCH_INDEX_PATH));
        }

        // Handle cache
        if($request->getContext()->getInitParameter(_Core::CACHE)) {

            // Get the cache
            $cache = $request->getContext()->getCache();
            // Clear the menu cache
            $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('menu'));             
            // Clear the page cache
            $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('page'));
        }


        // Return to index
        return $mapping->findForward("success");
    }

}
?>